package com.zx._03_并发.chapter_00_lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantDemo {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            pool.execute(new DataHandler(lock));
        }
    }

    static class DataHandler implements Runnable {

        private ReentrantLock lock;

        public DataHandler(ReentrantLock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            lock.lock();//第一重 上锁
            try {
                System.out.println("----------------");
                String name = Thread.currentThread().getName();
                System.out.println(name + "begin>>>>");
                Thread.sleep(1000L);
                lock.lock();//第二重 上锁
                try {
                    System.out.println(name + "..........................");

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();//第二重 解锁
                }
                System.out.println(name + "end  <<<<");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//第一重 解锁
            }

        }
    }

}
